package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XuechengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseInfoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {
    @Autowired
    private CourseBaseMapper courseBaseMapper;
    @Resource
    private CourseMarketMapper courseMarketMapper;
    @Resource
    private CourseCategoryMapper courseCategoryMapper;
    @Resource
    private TeachplanMediaMapper teachplanMediaMapper;
    @Resource
    private TeachplanMapper teachplanMapper;
    @Resource
    private CourseTeacherMapper courseTeacherMapper;
    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId,PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        LambdaQueryWrapper<CourseBase> queryWrapper=new LambdaQueryWrapper<>();

        //拼接查询条件
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),CourseBase::getName,
                queryCourseParamsDto.getCourseName());//课程名称
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,
                queryCourseParamsDto.getAuditStatus());//课程审核状态
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),CourseBase::getStatus,
                queryCourseParamsDto.getPublishStatus());//课程发布状态
        queryWrapper.eq(CourseBase::getCompanyId,companyId);//机构id
        //分页参数
        Page<CourseBase> page=new Page<>(pageParams.getPageNo(), pageParams.getPageSize());

        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);
        //数据
        List<CourseBase> items = pageResult.getRecords();
        //总记录数
        long total = pageResult.getTotal();
        //封装返回数据
        PageResult<CourseBase> courseBasePageResult=new PageResult<>(items,total,pageParams.getPageNo(),pageParams.getPageSize());
        return courseBasePageResult;
    }

    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto dto) {
        //数据合法性校验
        if (StringUtils.isBlank(dto.getName())) {
//            throw new RuntimeException("课程名称为空");
            throw new XuechengPlusException("课程名称为空");
        }


        if (StringUtils.isBlank(dto.getMt())) {
//            throw new RuntimeException("课程分类为空");
            throw new XuechengPlusException("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getSt())) {
//            throw new RuntimeException("课程分类为空");
            throw new XuechengPlusException("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getGrade())) {
//            throw new RuntimeException("课程等级为空");
            throw new XuechengPlusException("课程等级为空");
        }

        if (StringUtils.isBlank(dto.getTeachmode())) {
//            throw new RuntimeException("教育模式为空");
            throw new XuechengPlusException("教育模式为空");
        }

        if (StringUtils.isBlank(dto.getUsers())) {
//            throw new RuntimeException("适应人群为空");
            throw new XuechengPlusException("适应人群为空");
        }

        if (StringUtils.isBlank(dto.getCharge())) {
//            throw new RuntimeException("收费规则为空");
            throw new XuechengPlusException("收费规则为空");
        }
        //插入课程基本信息
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(dto,courseBase);//属性值一样则拷贝
        //设置审核状态
        courseBase.setAuditStatus("202002");
        //设置发布状态
        courseBase.setStatus("203001");
        //机构id
        courseBase.setCompanyId(companyId);
        //添加时间
        courseBase.setCreateDate(LocalDateTime.now());
        //插入课程基本信息表
        int insert = courseBaseMapper.insert(courseBase);
        if(insert<=0){
//            throw new RuntimeException("新增课程基本信息失败");
            throw new XuechengPlusException("新增课程基本信息失败");
        }
        //插入课程营销信息
        CourseMarket courseMarket = new CourseMarket();
        Long courseBaseId = courseBase.getId();
        BeanUtils.copyProperties(dto,courseMarket);
        courseMarket.setId(courseBaseId);
        int i = saveCourseMarket(courseMarket);
        if(i<=0){
//            throw new RuntimeException("保存课程营销信息失败");
            throw new XuechengPlusException("保存课程营销信息失败");
        }
        //查询课程基本信息及营销信息并返回
        return getCourseBaseInfo(courseBaseId);
    }

    //根据课程id查询课程基本信息，包括基本信息和营销信息
    public CourseBaseInfoDto getCourseBaseInfo(Long courseBaseId) {
        CourseBase courseBase = courseBaseMapper.selectById(courseBaseId);
        if(courseBase==null){
            return null;
        }
        CourseMarket courseMarket = courseMarketMapper.selectById(courseBaseId);
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        if(courseMarket!=null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }
        //查询分类名称
        CourseCategory courseCategoryMt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategoryMt.getName());
        CourseCategory courseCategorySt = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategorySt.getName());

        return courseBaseInfoDto;
    }

    private int saveCourseMarket(CourseMarket courseMarket) {
        //收费规则合法性校验
        String charge = courseMarket.getCharge();
        if(StringUtils.isBlank(charge)){
//            throw new RuntimeException("收费规则没有选择");
            throw new XuechengPlusException("收费规则没有选择");
        }
        if(charge.equals("201001")){//如果收费规则为收费，但价格为空或价格小于0
            if(courseMarket.getPrice()==null||courseMarket.getPrice()<=0||courseMarket.getOriginalPrice()==null||courseMarket.getOriginalPrice()<=0){
//                throw new RuntimeException("课程为收费价格不能为空且必须大于0");
                throw new XuechengPlusException("课程为收费价格不能为空且必须大于0");

            }
        }
        //根据id从课程营销表中查询
        CourseMarket courseMarketObj = courseMarketMapper.selectById(courseMarket.getId());
        if(courseMarketObj==null){//如果表中没用则为新增
            return courseMarketMapper.insert(courseMarket);
        }else {//如果有则为更新
            BeanUtils.copyProperties(courseMarket,courseMarketObj);
            courseMarketObj.setId(courseMarket.getId());
            return courseMarketMapper.updateById(courseMarketObj);
        }
    }

    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto) {
        //数据合法性校验
        //本机构只能修改本机构的课程
        Long id = editCourseDto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(id);
        if(courseBase==null){
            throw new XuechengPlusException("课程不存在");
        }
        if(!companyId.equals(courseBase.getCompanyId())){
            throw new XuechengPlusException("本机构只能修改本机构的课程");
        }
        //封装基本信息的数据
        BeanUtils.copyProperties(editCourseDto,courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
        //更新课程基本信息
        int i = courseBaseMapper.updateById(courseBase);
        //封装营销信息的数据
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto,courseMarket);
        saveCourseMarket(courseMarket);
        //查询课程信息
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(id);
        return courseBaseInfo;
    }

    @Transactional
    @Override
    public void deleteCourse(Long id) {
        CourseBase courseBase = courseBaseMapper.selectById(id);
        String auditStatus = courseBase.getAuditStatus();
        if(!auditStatus.equals("202002"))
            throw new XuechengPlusException("删除审核状态为未提交时才可以删除课程");
        int i = courseBaseMapper.deleteById(id);
        if(i<=0){
            throw new XuechengPlusException("删除课程失败");
        }

        int i1 = courseMarketMapper.deleteById(id);
       /* if(i1<=0){
            throw new XuechengPlusException("删除课程失败");
        }*/
        LambdaQueryWrapper<Teachplan> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,id);
        int delete = teachplanMapper.delete(queryWrapper);
       /* if(delete<=0){
            throw new XuechengPlusException("删除课程失败");
        }*/
        LambdaQueryWrapper<TeachplanMedia> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.eq(TeachplanMedia::getCourseId,id);
        int delete1 = teachplanMediaMapper.delete(queryWrapper1);
        /*if(delete1<=0){
            throw new XuechengPlusException("删除课程失败");
        }*/
        LambdaQueryWrapper<CourseTeacher> queryWrapper2=new LambdaQueryWrapper<>();
        queryWrapper2.eq(CourseTeacher::getCourseId,id);
        int delete2 = courseTeacherMapper.delete(queryWrapper2);
        /*if(delete2<=0){
            throw new XuechengPlusException("删除课程失败");
        }*/
    }
}
